package com.share.lottery.activity;

import java.util.List;
import org.apache.http.cookie.Cookie;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lidroid.xutils.util.LogUtils;
import com.share.lottery.R;
import com.share.lottery.base.BaseActivity;
import com.share.lottery.base.BaseApplication;
import com.share.lottery.base.Constants;
import com.share.lottery.http.BaseController;
import com.share.lottery.model.AdvertBean;
import com.share.lottery.model.User;
import com.share.lottery.model.UserInfo;
import com.share.lottery.utils.StringUtil;

/**
 * 广告详情
 * 
 * @author lmj
 * 
 */
public class AdvertDetail extends BaseActivity {

	private String url0 = "";
	private WebView mWebView;
	private ProgressBar mProgressBar;
	private AdvertBean advertBean;
	private String titleStr;
	private InputMethodManager imm;
	private AdvertDetail mContext;
	private TextView titleTv;
	private String BULLET_ID = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	
		mContext = this;
		setContentView(R.layout.webview);

		advertBean = (AdvertBean) getIntent().getSerializableExtra("advBean");
		if (advertBean != null) {
			url0 = advertBean.getPHOTO_ADDR();
			if (!StringUtil.isNullOrEmpty(url0)) {
				UserInfo bean = Constants.getUserBean();
				if (url0.contains("?")) {
					url0 = url0 + "&LOGIN_TOKEN=" + bean.getUserId();
				} else {
					url0 = url0 + "?LOGIN_TOKEN=" + bean.getUserId();
				}
			}
			titleStr = advertBean.getTITLE();
			if (StringUtil.isNullOrEmpty(titleStr)) {
				titleStr = "";
			}
		} else {
			url0 = (String) getIntent().getSerializableExtra("url");
		}

		LogUtils.e("url0==========" + url0);

		if (!StringUtil.isNullOrEmpty(url0) && url0.contains("BULLET_ID=")) {

			String idStr = url0.substring(url0.indexOf("BULLET_ID="));

			if (idStr != null && idStr.length() > 0) {
				BULLET_ID = idStr.substring(idStr.indexOf("=") + 1);
			}

		}

		synCookies(AdvertDetail.this, url0);

		init();
		inintWebView();
		mLoadUrl(url0);

		LogUtils.e("");

		// 软键盘管理类
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

		// // 初始化基本视图
		// initFootView();
		// // 初始化表情视图
		// initGridView();

	}

	@SuppressLint("SetJavaScriptEnabled")
	private void inintWebView() {
		mWebView = (WebView) findViewById(R.id.webview);
		mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setSupportZoom(true);
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

		/*** 打开本地缓存提供JS调用 **/
		mWebView.getSettings().setDomStorageEnabled(true);
		// Set cache size to 8 mb by default. should be more than enough
		mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
		String appCachePath = getApplicationContext().getCacheDir()
				.getAbsolutePath();
		mWebView.getSettings().setAppCachePath(appCachePath);
		mWebView.getSettings().setAllowFileAccess(true);
		mWebView.getSettings().setAppCacheEnabled(true);

		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub

				super.onPageStarted(view, url, favicon);
				LogUtils.e("url===" + url);

			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {

				String endStr = url.substring(url.lastIndexOf("/") + 1);

				if (endStr.contains("json=")) {
					String json = url.substring(url.indexOf("json="));
					LogUtils.e("json===" + json);

					if (!StringUtil.isNullOrEmpty(json)) {
						json = json.replace("json=", "");
					} else {
						return true;
					}

					// Intent intent = new Intent(AdvertDetail.this,
					// LuntanReplyActivity.class);
					// intent.putExtra("json", json);
					// startActivityForResult(intent, 100);
					return true;
				} else if (endStr.contains("bullet_info.jsp")) {
					Intent intent = new Intent(AdvertDetail.this,
							AdvertDetail.class);
					intent.putExtra("url", url);
					startActivity(intent);
					overridePendingTransition(R.anim.in_from_right,
							R.anim.out_to_right);
					return true;
				} else if (endStr.contains("createBullet.jsp")) {

					// Intent intent = new Intent(AdvertDetail.this,
					// LuntanReplyActivity1.class);
					// startActivityForResult(intent, 100);

				} else if (endStr.contains("open")) {
					// Intent intent = new Intent(AdvertDetail.this,
					// AdvertDetail_Common.class);
					// intent.putExtra("url", url);
					// startActivity(intent);
					// overridePendingTransition(R.anim.in_from_right,
					// R.anim.out_to_right);
					return true;
				} else {
					view.loadUrl(url);
				}

				return true;
			}
		});
		mWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				mProgressBar.setProgress(newProgress);
				mProgressBar.postInvalidate();
				if (newProgress == 100) {
					mProgressBar.setVisibility(View.GONE);
				}
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {

				// 设置当前activity的标题栏
				titleTv.setText(title);

				super.onReceivedTitle(view, title);

			}

		});

		// final Handler mHandler = new Handler();
		// mWebView.addJavascriptInterface(new Object() {
		// public void clickOnAndroid(final String order) {
		//
		// mHandler.post(new Runnable() {
		// public void run() {
		// Intent intent = new Intent(AdvertDetail.this,
		// BulletInfo.class);
		// intent.putExtra("advBean", advertBean);
		// intent.putExtra("url", order);
		// startActivity(intent);
		// }
		// });
		// }
		// }, "gopage");

	}

	@Override
	protected void onResume() {
		super.onResume();
		// if (mGridView.getVisibility() == View.VISIBLE) {
		// // 隐藏表情
		// hideFace();
		// }

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
		// mWebView.goBack();
		// return true;
		// } else {
		// finish();
		// }
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 初始化title
	 */
	public void initTitle() {
		// TODO Auto-generated method stub

		ImageButton titleLeftImg = (ImageButton) findViewById(R.id.title_left_img);
		ImageButton titleRightImg = (ImageButton) findViewById(R.id.title_right_img);
		titleTv = (TextView) findViewById(R.id.title_tv_center);

		titleLeftImg.setImageResource(R.drawable.back);
		titleTv.setText(titleStr);
		titleRightImg.setVisibility(View.VISIBLE);

		titleLeftImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});

		if (advertBean != null) {
			titleRightImg.setVisibility(View.GONE);
		}
	}

	private void mLoadUrl(String url) {
		if (mWebView != null) {
			mWebView.loadUrl(url);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mContext = null;
		super.onDestroy();
		overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
	}

	/**
	 * 同步一下cookie
	 */
	public static void synCookies(Context context, String url) {

		CookieSyncManager.createInstance(BaseApplication.getInstance());
		CookieManager cookieManager = CookieManager.getInstance();
		// cookieManager.setAcceptCookie(true);
		// cookieManager.removeSessionCookie();// 移除

		List<Cookie> cookies = BaseController.httpUtils.getHttpClient()
				.getCookieStore().getCookies();

		if (cookies != null) {
			for (Cookie cookie : cookies) {
				String cookieStr = cookie.getName() + "=" + cookie.getValue()
						+ ";domain=" + cookie.getDomain();
				cookieManager.setCookie(url, cookieStr);
			}
		}

		CookieSyncManager.getInstance().sync();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == 100) {
			if (resultCode == 1) {
				mWebView.reload();
			}
		}
	}

	@Override
	public void findView() {
	
		
	}

	@Override
	public void getData() {
		
		
	}


	public void setData() {
	
		
	}

	@Override
	public void setonCliker() {
		// TODO Auto-generated method stub
		
	}


	
}
